import { _decorator, Component, MeshRenderer, assetManager, Texture2D, ImageAsset, resources } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('RemoteTextureLoader')
export class RemoteTextureLoader extends Component {

    @property(MeshRenderer)
    meshRenderer: MeshRenderer;

    start() {
        this.meshRenderer = this.node.getComponent(MeshRenderer)


        const imageUrl = 'http://localhost/floormetrail.jpg';

        try {
            assetManager.loadAny([{ url: 'http://localhost/floormetrail.jpg' }, { url: 'http://localhost/floormetrail.jpg' }], {}, (err, assets) => {
                console.log('======================loadWithJson=======================');
                console.log('err:', err);
                console.log('assets:', assets);
            })

        } catch (e) {

            console.log('catch:', e);
        }


        assetManager.loadRemote(imageUrl, { key: 'map001' }, (err, imageAsset: ImageAsset) => {
            if (err) {
                console.error('image load error', err);
                return;
            }

            const texture = new Texture2D();
            //重置材质,必须有的方法
            texture.reset({
                width: imageAsset.width,
                height: imageAsset.height,
                format: Texture2D.PixelFormat.RGBA8888,
            });
            texture.image = imageAsset;
            const material = this.meshRenderer.getMaterialInstance(0);
            material.setProperty('mainTexture', texture);

        });
    }

    /** 加载多张图片并拼接
     
    import { _decorator, Component, ImageAsset, assetManager, SpriteFrame, Texture2D, Sprite } from 'cc';
    const { ccclass, property } = _decorator;
    @ccclass('ImageCombiner')
    export class ImageCombiner extends Component {

    // 需要拼接的图片资源数组（示例中硬编码路径，实际可按需动态加载）
    private imageUrls: string[] = [
        'textures/image1', // resources 目录下的图片
        'textures/image2',
        'http://remote-server.com/image3.jpg' // 远程图片
    ];

    start() {
        // 1. 加载所有图片资源
        this.loadAllImages(this.imageUrls).then((imageAssets: ImageAsset[]) => {
            // 2. 拼接图片
            const combinedImage = this.combineImages(imageAssets);
            
            // 3. 创建 SpriteFrame 并应用到组件
            const sprite = this.node.getComponent(Sprite);
            if (sprite && combinedImage) {
                const texture = new Texture2D();
                texture.image = combinedImage;
                sprite.spriteFrame = SpriteFrame.createWithTexture(texture);
            }
        });
    }

    //加载所有图片资源
    private loadAllImages(urls: string[]): Promise<ImageAsset[]> {
        const promises = urls.map(url => {
            if (url.startsWith('http')) {
                // 加载远程图片
                return new Promise<ImageAsset>((resolve, reject) => {
                    assetManager.loadRemote(url, (err, imageAsset: ImageAsset) => {
                        err ? reject(err) : resolve(imageAsset);
                    });
                });
            } else {
                // 加载本地 resources 图片
                return new Promise<ImageAsset>((resolve, reject) => {
                    resources.load(url, ImageAsset, (err, imageAsset: ImageAsset) => {
                        err ? reject(err) : resolve(imageAsset);
                    });
                });
            }
        });
        return Promise.all(promises);
    }

    //拼接图片（横向排列示例）
    private combineImages(imageAssets: ImageAsset[]): ImageAsset | null {
        if (imageAssets.length === 0) return null;

        // 1. 计算总画布尺寸（示例为横向拼接）
        let totalWidth = 0;
        let maxHeight = 0;
        imageAssets.forEach(asset => {
            totalWidth += asset.width;
            maxHeight = Math.max(maxHeight, asset.height);
        });

        // 2. 创建离屏 Canvas
        const canvas = document.createElement('canvas');
        canvas.width = totalWidth;
        canvas.height = maxHeight;
        const ctx = canvas.getContext('2d')!;

        // 3. 逐个绘制图片
        let currentX = 0;
        imageAssets.forEach(asset => {
            const img = new Image();
            img.src = asset.dataUrl; // 获取图片的 Base64 数据
            ctx.drawImage(img, currentX, 0, asset.width, asset.height);
            currentX += asset.width;
        });

        // 4. 生成新的 ImageAsset
        const combinedImageAsset = new ImageAsset(canvas.toDataURL());
        return combinedImageAsset;
    }
}
     */
}
